package backTrack;

import java.util.*;

public class ds47 {
    public static void main(String[] args) {
        System.out.println(permute(new int[]{1,2,1}));
    }
    public static List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        int[] used = new int[nums.length];
        Arrays.sort(nums);
        dfs(nums, used, ans, path);
        return ans;
    }
    public static void dfs(int[] nums, int[] used, List<List<Integer>> ans, List<Integer> path){
        if(path.size() == nums.length){
            ans.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if(i != 0 && used[i - 1] == 0 && nums[i] == nums[i - 1])
                continue;
            if(used[i] == 0){
                used[i] = 1;
                path.add(nums[i]);
                dfs(nums, used, ans, path);
                used[i] = 0;
                path.remove(path.size() - 1);
            }
        }
    }
}
